package com.gudaomai.ekproject.web;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.RetEntity;
import com.gudaomai.ekproject.entity.Role;
import com.gudaomai.ekproject.entity.RoleInput;
import com.gudaomai.ekproject.service.IRoleService;
import com.gudaomai.ekproject.web.BaseController;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@RestController
@RequestMapping("/ekproject/role")
public class RoleController extends BaseController {

	@Autowired
	IRoleService roleServ;
	@Autowired
	protected MessageSource messageSource;

	/**
	 * 新加角色 1. 输入检查
	 * 
	 * @param role
	 * @return TODO:complete 新加角色 1. 输入检查
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public RetEntity add(@RequestBody @Validated RoleInput role) throws BeansException, CommonException {

		RetEntity entity = new RetEntity();

		// 查询当前数据库是否存在该记录
		if (roleServ.isExist(role.getRoleName())) {
			// 若查询记录结果数大于零，设置状态码为201 @see CommonConstant MsgConstant
			throw new CommonException(CommonConstant.RESULT_CODE_CREATED,
					getMessage(MsgConstant.RET_ROLE_ADD_ALREADY_EXIST));
		} else {
			// 否则，插入该条记录，并设置状态码为200 @see CommonConstant MsgConstant
			Role role1 = new Role();
			BeanUtils.copyProperties(role, role1);
			role1.setId(IdWorker.get32UUID());
			roleServ.insert(role1);
			entity.setRetCode(CommonConstant.RESULT_CODE_OK);
			entity.setRetMessage(MsgConstant.RET_ROLE_ADD_SUCCESS);
		}
		// 返回状态信息
		return entity;
	}
}
